<?php

namespace App\Models;

use App\Services\WXBizDataCrypt;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Auth;

class User extends Authenticatable implements JWTSubject    # 这里别忘了加
{

    use Notifiable;
    // Rest omitted for brevity
    protected $table = 'user';
    public $timestamps = false;
    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }


    static function wxLogin($code,$encryptedData,$iv)
    {
        $appId = config('weChart.AppID');
        $appSecret = config('weChart.AppSecret');
        $apiUrl = 'https://api.weixin.qq.com/sns/jscode2session';
        $api_url = $apiUrl . '?appid=' . $appId . '&secret=' . $appSecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $result = file_get_contents($api_url);
        $result = json_decode($result,true);
        $openid = $result['openid'];
        $session_key = $result['session_key'];
        //更新用户信息
        $userphone = self::getUserPhone($appId,$session_key,$encryptedData,$iv);
        $userphone = json_decode($userphone,true);
        if (!$userphone){
            return false;
        }
        $user = self::where('openid',$openid)->first();
        if (!$user){
            //随机生成name
           $user_nickname = 'CCF_'.rand_name();
           $user_headimgurl = config('weChart.default_img');
            $uid = DB::table('user')->insertGetId([
                'openid' => $openid,
                'user_phone'=>$userphone['phoneNumber'],
                'create_time' => time(),
                'user_nickname' => $user_nickname,
                'user_headimgurl' => $user_headimgurl,
                'user_sign'=>'天生我才必有用'
            ]);
            return User::where('id',$uid)->first();
        }
        return $user;
    }

    static function getUserPhone($appid,$sessionKey,$encryptedData,$iv){
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            return $data;
        } else {
            return false;
        }
    }


    //查找所有会员
    public function getMemberList($page,$pageSize){
        $res = DB::table('user')
            ->join('sports_test', 'user.id', '=', 'sports_test.user_id')
            ->where('sports_test.target',1)
            ->where('user.level',1)
            ->select('user.user_name','user.play_img','user.position', 'sports_test.*')
            ->offset(($page-1)*$pageSize)
            ->limit($pageSize)
            ->get();
         foreach($res as $k=>&$v){
                 $v->position = self::getPosition($v->position);
         }
       return $res;
    }
    //查找最佳的优秀球员
    public static function getBest(){

        $res = DB::table('user')
            ->join('sports_test', 'user.id', '=', 'sports_test.user_id')
            ->where('sports_test.target',1)
            ->where('user.is_best',1)
            ->select('user.user_name','user.user_headimgurl','user.play_img','user.position', 'sports_test.*')
//            ->limit(,$pageSize)
            ->get();
        foreach($res as $k=>&$v){
            $v->position = self::getPosition($v->position);
        }
        return $res;
    }

    //解决位置
    static function getPosition($position){
        if (empty(json_decode($position))){
            return $position;
        }
       return  $position = json_decode($position)[0].'/'.json_decode($position)[1] ?? '';
    }
    //更具id找姓名
    static function getNameById($id){
        return self::where('id',$id)->value('user_name');
    }

    //更具id找姓名
    static function getNumById($id){
        return self::where('id',$id)->value('user_num');
    }

    //修改用户信息
    static function updateUser($id,$user_nickname,$pic){
       return self::where('id',$id)->update(['user_nickname'=>$user_nickname,'user_headimgurl'=>$pic]);
    }

    //判断当前手机号是否是该用户
    static function queryTel($tel){
       return self::where('user_phone',$tel)->first();
    }


    public static function getDetailUser($id){
        //学员信息
        $user_info = User::where('id',$id)->first(['user_name','play_img','user_img','user_video','position','sport_status','evaluate']);
        //查询用户体测条数
        $num = SportsTest::where('user_id',$id)->count();
        //体测
        $test = SportsTest::where('user_id',$id)->where('target',1)->first(['long_jump','sargent_jump','arm_spread','finger_span','point','age']);
            $user_info->long_jump = $test->long_jump ?? '';
            $user_info->sargent_jump = $test->sargent_jump ?? '';
            $user_info->arm_spread = $test->arm_spread ?? '';
            $user_info->finger_span = $test->finger_span ?? '';
            $user_info->point = $test->point ?? '';
            $user_info->user_img = json_decode($user_info->user_img) ?? '';
            $user_info->user_video = json_decode($user_info->user_video) ?? '';
            $user_info->age = $test->age ?? '';
            $user_info->sport_status = $user_info->sport_status ?? 0;
            $user_info->id = $user_info->user_id;
            $user_info->sport_num = $num;
            $user_info->evaluate = $user_info->evaluate ?? '';
            $user_info->position = self::getPosition($user_info->position);
        return $user_info;
    }


    static function switchSport($uid,$status){
         self::where('id',$uid)->update(['sport_status'=>$status]);
         return true;
    }

        //对应关系
        public function team()
        {
            return $this->hasOne('App\Models\Team','id','team_id');
        }
}
